﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 商户收藏关注
    /// </summary>
    [Route("admin/merchant/favorite")]
    [ApiController]
    public class MerchantFavoriteController : ControllerBase
    {
        private readonly IMerchantFavoriteService _merchantFavoriteService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public MerchantFavoriteController(IMerchantFavoriteService merchantFavoriteService, IUserService userService, IMapper mapper)
        {
            _merchantFavoriteService = merchantFavoriteService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/admin/merchant/favorite/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("MerchantFavorite", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var resultFrom = await _merchantFavoriteService.QueryAsync(x => x.Id == id, WriteRoRead.Write);
            if (resultFrom == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //根据字段进行塑形
            var result = resultFrom.ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/merchant/favorite?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("MerchantFavorite", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表
            var list = await _merchantFavoriteService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Merchant != null && x.Merchant.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var result = _mapper.Map<IEnumerable<MerchantFavoriteDto>>(list).ShapeData(searchParam.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/merchant/favorite/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("MerchantFavorite", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            if (!await _merchantFavoriteService.ExistsAsync<MerchantFavorite>(x => x.Id == id))
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _merchantFavoriteService.DeleteAsync(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/admin/merchant/favorite?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("MerchantFavorite", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _merchantFavoriteService.DeleteAsync(x => arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 获取分页列表
        /// 示例：/merchant/favorite?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/merchant/favorite")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<MerchantFavoriteMemberDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<MerchantFavoriteMemberDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _merchantFavoriteService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据列表
            var list = await _merchantFavoriteService.QueryMemberPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.MerchantId == merchantModel.Id
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.UserName != null && x.UserName.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //根据字段进行塑形，注意因为没有使用AotoMapper，所以要转换成Enumerable
            var result = list.AsEnumerable<MerchantFavoriteMemberDto>().ShapeData(searchParam.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/merchant/favorite/1
        /// </summary>
        [HttpDelete("/merchant/favorite/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantDelete([FromRoute] long id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _merchantFavoriteService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }
            if (!await _merchantFavoriteService.ExistsAsync<MerchantFavorite>(x => x.Id == id && x.MerchantId == merchantModel.Id))
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }

            await _merchantFavoriteService.DeleteAsync(x => x.Id == id && x.MerchantId == merchantModel.Id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/merchant/favorite?ids=1,2,3
        /// </summary>
        [HttpDelete("/merchant/favorite")]
        [Authorize]
        public async Task<IActionResult> MerchantDeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _merchantFavoriteService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _merchantFavoriteService.DeleteAsync(x => x.MerchantId == merchantModel.Id && arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 普通账户调用接口========================
        /// <summary>
        /// 根据商家ID获取数据
        /// 示例：/account/merchant/favorite/1
        /// </summary>
        [HttpGet("/account/merchant/favorite/{id}")]
        public async Task<IActionResult> AccountGetById([FromRoute] int id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }
            //查询数据库获取实体
            var model = await _merchantFavoriteService.QueryAsync(x => x.UserId == userId && x.Merchant != null && x.Merchant.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<MerchantFavoriteDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/account/merchant/favorite?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/account/merchant/favorite")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<MerchantFavoriteDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _merchantFavoriteService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.UserId == userId
                && (x.Merchant != null && x.Merchant.IsLock == 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Merchant.Title != null && x.Merchant.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<MerchantFavoriteDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/account/merchant/favorite/1
        /// </summary>
        [HttpPost("/account/merchant/favorite/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountAdd([FromRoute] int id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            if (!await _merchantFavoriteService.ExistsAsync<Merchants>(x => x.Id == id))
            {
                return BadRequest(ResponseMessage.Error($"商户[{id}]不存在或已删除"));
            }
            //获取当前账户赋值
            MerchantFavoriteEditDto modelDto = new()
            {
                UserId = userId,
                MerchantId = id
            };
            //映射成DTO再返回，否则出错
            var result = await _merchantFavoriteService.AddAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/account/merchant/favorite/1
        /// </summary>
        [HttpDelete("/account/merchant/favorite/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountDelete([FromRoute] int id)
        {
            if (!await _merchantFavoriteService.ExistsAsync<Merchants>(x => x.Id == id))
            {
                return BadRequest(ResponseMessage.Error($"商户[{id}]不存在或已删除"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            var result = await _merchantFavoriteService.DeleteAsync(x => x.UserId == userId && x.MerchantId == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录
        /// 示例：/account/merchant/favorite?ids=1,2,3
        /// </summary>
        [HttpDelete("/account/merchant/favorite")]
        [Authorize]
        public async Task<IActionResult> AccountDeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _merchantFavoriteService.DeleteAsync(x => x.UserId == userId && arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion
    }
}
